<?php
/**
 * 代理发货
 */

namespace app\api\controller\v2;

use app\admin\model\User;
use app\common\controller\Api;
use app\common\model\AgentAdmin;
use app\common\model\AgentSendTips;
use app\common\model\AgentShipment;
use app\common\model\AgentShop;
use app\common\model\AgentStock;
use app\common\model\Goods;
use app\common\model\ShipRemind;
use app\common\validate\ShipOrder;
use think\Db;


class Ship extends Api {
	
	/**
	 * 代理及代理管理员的发货
	 */
	public function send() {
		//检测发货权限,重庆（战区，发展中心，提货点）,广东（宝能，火爆街）
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == User::LEVEL_USER) {
			//检测是不是代理的管理员
			$adminLevel = AgentAdmin::getAdminLevel($userId);
			if($adminLevel) {
				$userId = $adminLevel['user_id'];
				$level = $adminLevel['role'];
			}
		}
		
		$userModel = new User();
		if(!in_array($level, [$userModel::LEVEL_HEADQUARTERS, $userModel::LEVEL_CENTER, $userModel::LEVEL_WAREHOUSE])) {
			$this->error('当前帐号没有发货权限');
		}
		
		$postData = $this->request->post();
		$check = new ShipOrder();
		if(!$check->check($postData)) {
			$this->error($check->getError());
		}
		
		if($level != $userModel::LEVEL_HEADQUARTERS) {
			$sendAgent = AgentShop::get(['user_id' => $userId]);
			!$sendAgent && $this->error('你没有权限');
		} else {
			$sendAgent = '';
		}
		
		$numberList = $postData['number_list'];
		$destoryNumber = $postData['destroy_number'] ?? 0;
		if(!$numberList && !$destoryNumber) {
			$this->error('请输入发货数量或核销奖励数量');
		}
		
		$signAgent = AgentShop::get($postData['agent_id']);
		!$signAgent && $this->error('收货下级不存在');
		
		//重庆要选择配送员
		if($sendAgent && $sendAgent['area'] == User::AREA_OTHER && empty($postData['postman_id'])) {
			$this->error('请选择配送员');
		}
		
		$model = new \app\common\model\ShipOrder();
		$postmanId = $postData['postman_id'] ??'';
		$res = $model->sendGoods($signAgent['area'], $postData['ship_name'], $postData['ship_no'], $numberList, $signAgent, $sendAgent, $postmanId, $destoryNumber);
		
		$tipsRes = Db::name('agentSendTips')
			->where(['user_id' => $userId, 'agent_id' => $signAgent['id']])
			->update(['status' => AgentSendTips::STATUS_DONE, 'update_time' =>time()]);
		
		if($res){
			$this->success('发货成功');
		} else {
			$this->error($model->getError());
		}
		
		
	}
	
	
	/**
	 * 进出货订单
	 */
	public function order() {
		$type = $this->request->post('type', 'sign');
		$page = $this->request->post('page', 1, 'intval');
		
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == User::LEVEL_USER) {
			$adminLevel = AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] == User::LEVEL_USER) {
				$this->error('权限不足');
			}
			$userId = $adminLevel['user_id'];
			$level  = $adminLevel['role'];
		}
		
		if($level == User::LEVEL_HEADQUARTERS) {
			$shop['id'] = 0;
		} else {
			$shop = AgentShop::get(['user_id' => $userId]);
			!$shop && $this->error('权限不足');
		}
		
		
		
		$signId = '';
		$sendId = '';
		if($type == 'sign') {
			$signId = $shop['id'];
		} else {
			$sendId = $shop['id'];
		}
		
		$model = new \app\common\model\ShipOrder();
		$orders = $model->getOrder($page, $signId, $sendId);
		$this->success('查询成功', $orders);
	}
	
	/**
	 * 签收入库
	 */
	public function sign() {
		$id = $this->request->post('id', '', 'intval');
		$code = $this->request->post('code', '', 'intval');
		if(!$id || !$code) {
			$this->error('参数错误');
		}
		
		
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level == User::LEVEL_USER) {
			$adminLevel = AgentAdmin::getAdminLevel($userId);
			if($adminLevel) {
				$userId = $adminLevel['user_id'];
			}
		}
		$shop = AgentShop::get(['user_id' => $userId]);
		!$shop && $this->error('权限不足');
		
		
		
		$model = new \app\common\model\ShipOrder();
		$row = $model->find($id);
		!$row && $this->error('订单不存在');
		$row['sign_code'] != $code && $this->error('签收码错误');
		
		$res = $model->sign($row['no'], $shop['id'], $userId);
		if($res) {
			$this->success('入库成功');
		} else {
			$this->error($model->getError());
		}
	}
	
	/**
	 * 获取应发数量
	 */
	public function getSendNumber() {
		$agentId = $this->request->post('agent_id');
		!$agentId && $this->error('参数错误');
		
		
		$agent = AgentShop::get(['id' => $agentId]);
		!$agent && $this->error('代理不存在');
		//获取现在在售的商品
		$goods = Db::name('goods')->alias('g')
			->join('goodsSpec s', 'g.id = s.goods_id and s.status = 1', 'left')
			->where(['g.area' => ['in', [$agent['area'], 0]], 'g.status' => Goods::STATUS_SALE])
			->field('g.id as goods_id, g.name, ifnull(s.id, 0) as spec_id, s.name as spec_name')
			->select();
		
		
		$setting = Db::name('stockWarning')
			->where(['area' => $agent['area'], 'level' => $agent['role']])
			->field('goods_id, ifnull(spec_id, 0) as spec_id, number')
			->select();
		
		$globeSetting = [];
		if($setting) {
			foreach ($setting as $item) {
				$globeSetting[$item['goods_id'].'_'.$item['spec_id']] = $item['number'];
			}
		}
		
		$goodsSettigng= Db::name('agentStockSetting')
			->where(['agent_id' => $agentId])
			->field('goods_id, ifnull(spec_id, 0) as spec_id, number')
			->select();
		
		$agentSetting = [];
		if($goodsSettigng) {
			foreach ($goodsSettigng as $item) {
				$agentSetting[$item['goods_id'].'_'.$item['spec_id']] = $item['number'];
			}
		}
		
		if($goods) {
			$model = new AgentStock();
			foreach ($goods as &$item) {
				$count = $model->getAgentAndSubStock($agentId, $item['goods_id'], $item['spec_id']);
				$item['stock'] = $count['all_stock'] ?? 0;
				$item['max_number'] = $count['all_max_stock'] ?? 0;
				$item['number'] = $count ? $count['all_max_stock'] - $count['all_stock'] : 0;
			}
		}
		
		
		$this->success('查询成功', [
			'gift_number' => $agent['gift_number'],
			'goodsList' => $goods
		]);
	}
}